package weifei.live.simulation.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weifei.mall.entity.Goods;
import weifei.mall.entity.GoodsPicture;
import weifei.live.simulation.service.UserService;
import weifei.web.Result;


@RestController
@RequestMapping("/user")
public class GoodsUserController
{
    @Autowired
    private UserService userService;

    @Autowired
    private Goods dao_goods;


    @PostMapping("/sellGoods")
    public Result sellGoods(HttpServletRequest request, @Valid @RequestBody Goods goods)
    {
        var token = request.getHeader("token");
        var user_id = this.userService.getUserIDByToken(token);
        goods.setSellerId(user_id);
        if (!goods.insert())
            return Result.exception("商品发布失败，数据库出错");
        return Result.success("商品发布成功");
    }


    /**
     * @param pictureContent 图片使用 jpg格式
     * */
    @PostMapping("/uploadGoodsPicture")
    public Result uploadGoodsPicture(
            HttpServletRequest request,
            @RequestParam("goodsId") Integer goodsId,
            @RequestParam("picture") byte[] pictureContent
        )
    {
        var token = request.getHeader("token");
        var user_id = this.userService.getUserIDByToken(token);

        QueryWrapper<Goods> qw_goods = new QueryWrapper<>();
        qw_goods.eq(Goods.Column.ID.getName(), goodsId);
        var gp = this.dao_goods.selectOne(qw_goods);
        if (!gp.getSellerId().equals(user_id))
            return Result.failed("没有权限");

        QueryWrapper<GoodsPicture> qw_goods_picture = new QueryWrapper<>();
        qw_goods_picture.eq(GoodsPicture.Column.GoodsID.getName(), goodsId);
        int order = (int) new GoodsPicture().selectCount(qw_goods_picture);

        if (!new GoodsPicture(user_id, goodsId, order, pictureContent).insert())
            return Result.exception("图片上传失败，数据库出错");
        return Result.success("图片上传成功");
    }
}


